package com.hnit.care.config;

import com.alibaba.fastjson.JSONObject;
import com.hnit.care.entity.Coredata;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import javax.websocket.OnMessage;
import java.io.IOException;

@Component
public class WebSocketHandler extends TextWebSocketHandler {

    WebSocketSession webSocketSession;
    TextMessage textMessage;
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 连接建立后执行的逻辑
        System.out.println("WebSocket连接已建立");
        this.webSocketSession = session;
        //this.webSocketSession.sendMessage(new TextMessage("helllo"));
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 处理接收到的文本消息
       /* String receivedMessage = message.getPayload();
        System.out.println("接收到消息：" + receivedMessage);

        String str = "hello";
        // 发送消息给客户端
        String responseMessage = str;
        session.sendMessage(new TextMessage(responseMessage));*/
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        // 连接关闭后执行的逻辑
        System.out.println("WebSocket连接已关闭，原因：" + status.getReason());
    }

    @OnMessage
    public void onMessage(String message) throws IOException {
        // 发送消息给客户端
        this.webSocketSession.sendMessage(new TextMessage(message));

    }

    public void send(String message) throws IOException {
        this.webSocketSession.sendMessage(new TextMessage(message));
    }

    public void send(Coredata Coredata) throws IOException {
        String message = JSONObject.toJSONString(Coredata);
        this.webSocketSession.sendMessage(new TextMessage(message));
    }

}